package com.lagou.tomcat.servlet;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建人: yyn
 * 创建时间:2021/9/5 20:47
 */
public class ServletContext {
    private Map<String, Servlet> context = new HashMap<String, Servlet>();


    public ServletContext() {
        try {
            this.contextInitialize();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void contextInitialize() throws DocumentException, ClassNotFoundException, IllegalAccessException,
            InstantiationException {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        // 获取根节点
        Element rootElement = document.getRootElement();
        List<Element> servletList = rootElement.selectNodes("//servlet");

        for (Element element : servletList) {
            Node servletNameNode = element.selectSingleNode("//servlet-name");
            String servletName = servletNameNode.getText();
            Node servletClassNode = element.selectSingleNode("//servlet-class");
            String servletClass = servletClassNode.getText();

            Element servletMapping =
                    (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName +
                            "']");
            Node urlPatternNode = servletMapping.selectSingleNode("//url-pattern");
            String urlPattern = urlPatternNode.getText();

            Class<?> aClass = Class.forName(servletClass);
            Servlet o = (Servlet) aClass.newInstance();
            context.put(urlPattern, o);
        }
    }


    public Servlet getServlet(String uri){
        return context.get(uri);
    }
}
